﻿using Engine;
using Engine.Graphics;
using Game;

namespace SAGhoul.ParticleSystem
{
	public class BizarreAttackParticleSystem : ParticleSystem<BizarreAttackParticleSystem.Particle>
	{
		public class Particle : Game.Particle
		{
			public Vector3 Velocity;
			public float TimeToLive;
			public float Duration;
		}

		public Game.Random m_random = new();
		public SubsystemTerrain m_subsystemTerrain;
		public Vector3 m_position;
		public float m_time;

		public BizarreAttackParticleSystem(SubsystemTerrain terrain, Vector3 position, float range)
			: base(60)
		{
			m_subsystemTerrain = terrain;
			m_position = position;
			Texture = ContentManager.Get<Texture2D>("Textures/FireworksParticle");
			TextureSlotsCount = 2;
			for (int i = 0; i < Particles.Length; i++)
			{
				Particle obj = Particles[i];
				obj.IsActive = true;
				obj.Position = position;
				obj.Color = new Color(224, 210, 0, 155);
				obj.Size = new Vector2(0.35f);
				obj.TimeToLive = obj.Duration = m_random.Float(0.2f, 0.8f);
				Vector3 v0 = Vector3.UnitX;
				Matrix matrix = Matrix.CreateRotationY(i * MathUtils.DegToRad(360f) / Particles.Length);
				Vector3.Transform(ref v0, ref matrix, out Vector3 v1);
				float speed = range / obj.Duration;
				obj.Velocity = speed * Vector3.Normalize(v1);
			}
		}

		public override bool Simulate(float dt)
		{
			dt = MathUtils.Clamp(dt, 0f, 0.1f);
			m_time += dt;
			bool flag = false;
			for (int i = 0; i < Particles.Length; i++)
			{
				Particle particle = Particles[i];
				if (!particle.IsActive)
				{
					continue;
				}
				flag = true;
				float progress = (particle.Duration - particle.TimeToLive) / particle.Duration;
				float y = progress >= 0.25f ? -12f : 15f;
				particle.Position += particle.Velocity * dt;
				particle.Velocity.Y += y * dt;
				particle.TimeToLive -= dt;
				particle.TextureSlot = (int)(3.99f * particle.TimeToLive / particle.Duration);
				particle.FlipX = m_random.Sign() > 0;
				particle.FlipY = m_random.Sign() > 0;
				if (particle.TimeToLive <= 0f || particle.Size.X <= 0f)
				{
					particle.IsActive = false;
					continue;
				}
				int cellValue = m_subsystemTerrain.Terrain.GetCellValue(Terrain.ToCell(particle.Position.X), Terrain.ToCell(particle.Position.Y), Terrain.ToCell(particle.Position.Z));
				int num2 = Terrain.ExtractContents(cellValue);
				if (num2 == 0)
				{
					continue;
				}
				Block block = BlocksManager.Blocks[num2];
				if (block.IsCollidable_(cellValue))
				{
					particle.IsActive = true;
				}
			}
			return !flag;
		}
	}
}
